let express = require('express');
let router = express.Router();
let connection = require('../dataBase');
const { createToken } = require('../jwt');
const Result = require('../result');
const { verifyToken } = require('../jwt');
const { insertSql, updateSql } = require('../../utils');

// // 注册
router.post('/public/register', function (req, res) {
  const sql = insertSql('account', req.body);
  connection.query(sql, (err, data) => {
    if (err) {
      if (err.errno === 1062) {
        return new Result(res, 1201).fail();
      }
      return new Result(res, 1200).fail();
    }
    return new Result(res, 200, null, '注册成功').success();
  });
});

// // 登录
router.post('/public/login', function (req, res) {
  const account = req.query;
  const token = createToken(req.query);
  const sql = `select * from account where email="${account.email}" and password = "${account.password}"`;
  connection.query(sql, (err, data) => {
    if (err) {
      console.log(err);
      return new Result(res, 1200).fail();
    }
    if (data.length === 0) {
      return new Result(res, 404).fail(200);
    }
    return new Result(
      res,
      200,
      {
        token,
        account: data[0],
      },
      '登录成功',
    ).success();
  });
});

// 自动登录
router.get('/getAccount', function (req, res) {
  try {
    let account = verifyToken(req.headers.authorization);
    const sql = `select * from account where email="${account.email}" and password = "${account.password}"`;
    connection.query(sql, (err, data) => {
      if (err) {
        return new Result(res, 1200).fail(500);
      }
      //   获取不到数据
      if (data.length === 0) {
        return new Result(res).fail(404);
      }
      return new Result(res, 200, data[0], '登录成功').success();
    });
  } catch (error) {
    return new Result(res, 1200).fail(500);
  }
});

router.post('/update', function (req, res) {
  try {
    const sql = updateSql('account', req.body.id, req.body);
    connection.query(sql, (err, data) => {
      if (err) {
        console.log(err);
        return new Result(res, 1200).fail(500);
      }
      return new Result(res, 200, data[0], '登录成功').success();
    });
  } catch (error) {
    return new Result(res, 1200).fail(500);
  }
});

module.exports = router;
